package com.lirh.mysql.service;

import com.lirh.mysql.dao.ReplyDao;
import com.lirh.mysql.entity.Reply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReplyServiceImpl {
    @Autowired
    private ReplyDao replyDao;

    public String insert(Reply reply){
        replyDao.insert(reply);
        return "ok";
    }

    public List<Reply> getallreply(int id){
        List<Reply> maps = replyDao.selectAll(id);
        List<Reply> clevel = maps.stream().filter(item -> item.getClevel()==1
        ).map(item1 -> {
            item1.setChildren(getChilds(item1, maps));
            return item1;
        }).sorted((s1, s2) -> {
            return (new Integer(s1.getShunxu()) == null ? 0 : s1.getShunxu()) - (new Integer(s2.getShunxu()) == null ? 0 : s2.getShunxu());
        }).collect(Collectors.toList());
        return clevel;

    }

    private List<Reply> getChilds(Reply root, List<Reply> maps){
        List<Reply> fatherid = maps.stream().filter(item -> item.getFatherid()==root.getId())
                .map(item1 -> {
                    item1.setChildren(getChilds(item1, maps));
                    return item1;
                }).sorted((s1, s2) -> {
                    return (new Integer(s1.getShunxu()) == null ? 0 : s1.getShunxu()) - (new Integer(s2.getShunxu()) == null ? 0 : s2.getShunxu());
                }).collect(Collectors.toList());
        return fatherid;
    }

}
